package com.hzhr.iot.cqgas.ds.service;

import com.hzhr.iot.core.constant.CommonOptions;
import com.hzhr.iot.core.util.HzhrDateUtil;
import com.hzhr.iot.core.util.HzhrTypeUtil;
import com.hzhr.iot.cqgas.ds.dao.device.custom.DevCollectDataCustomDao;
import com.hzhr.iot.cqgas.ds.dao.device.custom.DevCollectDeviceCustomDao;
import com.hzhr.iot.cqgas.ds.dao.device.custom.DeviceDao;
import com.hzhr.iot.cqgas.ds.dao.device.example.*;
import com.hzhr.iot.cqgas.ds.dao.oa.OaDao;
import com.hzhr.iot.cqgas.ds.dao.smartmeter.custom.SmDao;
import com.hzhr.iot.cqgas.ds.dao.smartmeter.custom.SmDeviceCustomDao;
import com.hzhr.iot.cqgas.ds.dao.toll.custom.TollGasUserCustomDao;
import com.hzhr.iot.cqgas.ds.dao.toll.example.TollGasUserDao;
import com.hzhr.iot.cqgas.ds.dao.user.custom.UserCustomDao;
import com.hzhr.iot.cqgas.ds.dao.user.example.UsrDeptDao;
import com.hzhr.iot.cqgas.ds.entity.device.*;
import com.hzhr.iot.cqgas.ds.entity.toll.TollGasUserEntity;
import com.hzhr.iot.cqgas.ds.entity.user.UsrDeptEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;

@Service
public class CollectDeviceService {
    @Autowired
    DevCollectDeviceDao devCollectDeviceDao;
    @Autowired
    SmDeviceCustomDao smDeviceCustomDao;
    @Autowired
    DevOptionsService devOptionsService;
    @Autowired
    DevCollectDeviceTypeDao devCollectDeviceTypeDao;
    @Autowired
    UsrDeptDao usrDeptDao;
    @Autowired
    DevIotDeviceDao devIotDeviceDao;
    @Autowired
    TollGasUserDao tollGasUserDao;
    @Autowired
    DevCollectDeviceCustomDao devCollectDeviceCustomDao;
    @Autowired
    DevCollectDataCustomDao devCollectDataCustomDao;
    @Autowired
    OaDao oaDao;
    @Autowired
    UserCustomDao userCustomDao;
    @Autowired
    DevDeviceInfoCardDao devDeviceInfoCardDao;
    @Autowired
    DevDeviceMaintenaceCardDao devDeviceMaintenaceCardDao;
    @Autowired
    DeviceDao deviceDao;
    @Autowired
    SmDao smDao;
    @Autowired
    TollGasUserCustomDao tollGasUserCustomDao;
    @Autowired
    TollOptionsService tollOptionsService;

    @Value("${companyId}")
    String companyId;

    private Logger logger = LoggerFactory.getLogger(CollectDeviceService.class);

    public void syncCollectDevice(Date startDate, Date endDate) {
        int addCount = 0;
        int updateCount = 0;
        long start = new Date().getTime();

        Map<String, Object> criteriaMap = new HashMap<>();
        if (startDate != null) criteriaMap.put("startDate", HzhrDateUtil.dateToStr(startDate));
        if (endDate != null) criteriaMap.put("endDate", HzhrDateUtil.dateToStr(endDate));
        List<Map<String, Object>> collectDevices = smDeviceCustomDao.selectCollectDevice(criteriaMap);

        //查询出物联网设备
        List<DevIotDeviceEntity> devIotDeviceEntities = devIotDeviceDao.selectByExample(null);
        Map<String, Integer> iotDevices = new HashMap<>();
        for (DevIotDeviceEntity devIotDeviceEntity :
                devIotDeviceEntities) {
            iotDevices.put(devIotDeviceEntity.getOutId(), devIotDeviceEntity.getId());
        }

        //查询出燃气用户
        List<TollGasUserEntity> tollGasUserEntities = tollGasUserDao.selectByExample(null);
        Map<String, TollGasUserEntity> gasUsers = new HashMap<>();
        for (TollGasUserEntity tollGasUserEntity :
                tollGasUserEntities) {
            gasUsers.put(tollGasUserEntity.getOutId(), tollGasUserEntity);
        }

        //查询出采集设备类型
        List<DevCollectDeviceTypeEntity> devCollectDeviceTypeEntities = devCollectDeviceTypeDao.selectByExample(null);
        Map<String, Integer> collectDeviceTypes = new HashMap<>();
        for (DevCollectDeviceTypeEntity devCollectDeviceTypeEntity :
                devCollectDeviceTypeEntities) {
            collectDeviceTypes.put(devCollectDeviceTypeEntity.getOutId(), devCollectDeviceTypeEntity.getId());
        }

        //查询部门
        List<UsrDeptEntity> usrDeptEntities = usrDeptDao.selectByExample(null);
        Map<String, UsrDeptEntity> userDepts = new HashMap<>();
        for (UsrDeptEntity userDeptEntity :
                usrDeptEntities) {
            userDepts.put(userDeptEntity.getCode(), userDeptEntity);
        }

        //查询选项
        String gprs = devOptionsService.getCode("COLLECT_DEVICE_CATEGORY", "GPRS_IOT_GAS_METER");
        String flowMeter = devOptionsService.getCode("COLLECT_DEVICE_CATEGORY", "FLOW_METER");
        String loraMeter = devOptionsService.getCode("COLLECT_DEVICE_CATEGORY", "LORA_METER");
        String bkMeter = devOptionsService.getCode("COLLECT_DEVICE_CATEGORY", "BK_METER");

        for (Map<String, Object> collectDevice :
                collectDevices) {
            try {
                String meterId = HzhrTypeUtil.object2string(collectDevice.get("METER_ID"));
                String meterNo = HzhrTypeUtil.object2string(collectDevice.get("METER_NO"));
                String installAddr = HzhrTypeUtil.object2string(collectDevice.get("INSTALL_ADDR"));
                String remoteMeterId = HzhrTypeUtil.object2string(collectDevice.get("REMOTE_METER_ID"));
                String mtId = HzhrTypeUtil.object2string(collectDevice.get("MT_ID"));
                String orgId = HzhrTypeUtil.object2string(collectDevice.get("ORG_ID"));
                String yqdzId = HzhrTypeUtil.object2string(collectDevice.get("YQDZ_ID"));
                String pressureUnit = HzhrTypeUtil.object2string(collectDevice.get("PRESSURE_UNIT"));
                String parentNodeId = HzhrTypeUtil.object2string(collectDevice.get("NODE_ID"));
                String c = collectDevice.get("CREATE_TIME").toString();

                if ("132".equals(remoteMeterId)) {
                    //如果lora表是由iot平台自建，则跳过
                    DevCollectDeviceExample devCollectDeviceExample = new DevCollectDeviceExample();
                    devCollectDeviceExample.createCriteria().andCodeEqualTo(meterNo).andCategoryCodeEqualTo("3").andOutIdIsNull().andIsValidEqualTo("1");
                    int count = devCollectDeviceDao.countByExample(devCollectDeviceExample);
                    if (count > 0) {
                        continue;
                    }
                }


                Date installTime = null;
                if (!StringUtils.isEmpty(c)) {
                    installTime = HzhrDateUtil.strToDate(c, "yyyy-MM-dd HH:mm:ss.ms");
                }

                String deptCode = orgId.replace("0000", "9-01");
                String resourceCode = orgId.replace("0000", "01000901");

                DevCollectDeviceExample devCollectDeviceExample = new DevCollectDeviceExample();
                devCollectDeviceExample.createCriteria().andOutIdEqualTo(meterId);
                List<DevCollectDeviceEntity> devCollectDataEntities = devCollectDeviceDao.selectByExample(devCollectDeviceExample);

                if (devCollectDataEntities.size() > 0) {
                    DevCollectDeviceEntity devCollectDeviceEntity = devCollectDataEntities.get(0);
                    devCollectDeviceEntity.setOutId(meterId);
                    devCollectDeviceEntity.setCode(meterNo);
                    devCollectDeviceEntity.setDes(installAddr);

                    if ("130".equals(remoteMeterId)) {
                        if (meterNo.startsWith("2066")) {
                            devCollectDeviceEntity.setCategoryCode(bkMeter);
                        } else {
                            devCollectDeviceEntity.setCategoryCode(gprs);
                        }
                    } else if ("132".equals(remoteMeterId)) {
                        devCollectDeviceEntity.setCategoryCode(loraMeter);
                    } else if ("134".equals(remoteMeterId)) {
                        devCollectDeviceEntity.setCategoryCode(flowMeter);
                    } else {
                        continue;
                    }

                    TollGasUserEntity tollGasUserEntity = gasUsers.get(yqdzId);
                    if (tollGasUserEntity != null) {
                        devCollectDeviceEntity.setGasUserId(tollGasUserEntity.getId());
                        devCollectDeviceEntity.setGasUserCode(tollGasUserEntity.getCode());
                        devCollectDeviceEntity.setGasUserAddress(tollGasUserEntity.getAddress());
                        devCollectDeviceEntity.setGasUserName(tollGasUserEntity.getName());
                    } else {
                        continue;
                    }

                    Integer typeId = collectDeviceTypes.get(mtId);
                    if (typeId != null) {
                        devCollectDeviceEntity.setTypeId(typeId);
                    } else {
                        devCollectDeviceEntity.setTypeId(0);
                    }

                    devCollectDeviceEntity.setIotDeviceId(iotDevices.get(parentNodeId));

                    UsrDeptEntity usrDeptEntity = userDepts.get(deptCode);
                    if (usrDeptEntity != null) {
                        devCollectDeviceEntity.setDeptId(usrDeptEntity.getId());
                        devCollectDeviceEntity.setDeptCode(usrDeptEntity.getCode());
                    } else {
                        devCollectDeviceEntity.setDeptId(0);
                    }

                    if ("1".equals(pressureUnit)) {
                        devCollectDeviceEntity.setPressureUnit("3");
                    }  else if ("2".equals(pressureUnit)) {
                        devCollectDeviceEntity.setPressureUnit("2");
                    } else if ("3".equals(pressureUnit)) {
                        devCollectDeviceEntity.setPressureUnit("1");
                    }

                    devCollectDeviceEntity.setCompanyId(Integer.parseInt(companyId));
                    devCollectDeviceEntity.setInstallTime(installTime);
                    devCollectDeviceEntity.setUpdateTime(new Date());
                    devCollectDeviceEntity.setUpdateUserId(0);
                    devCollectDeviceEntity.setResourceCode(resourceCode);
                    devCollectDeviceEntity.setIsValid(CommonOptions.YES_NO.YES);
                    devCollectDeviceEntity.setState("1");
                    devCollectDeviceDao.updateByPrimaryKey(devCollectDeviceEntity);

                    updateCount++;
                } else {
                    DevCollectDeviceEntity devCollectDeviceEntity = new DevCollectDeviceEntity();
                    devCollectDeviceEntity.setOutId(meterId);
                    devCollectDeviceEntity.setCode(meterNo);
                    devCollectDeviceEntity.setDes(installAddr);

                    if ("130".equals(remoteMeterId)) {
                        if (meterNo.startsWith("2066")) {
                            devCollectDeviceEntity.setCategoryCode(bkMeter);
                        } else {
                            devCollectDeviceEntity.setCategoryCode(gprs);
                        }
                    } else if ("132".equals(remoteMeterId)) {
                        devCollectDeviceEntity.setCategoryCode(loraMeter);
                    } else if ("134".equals(remoteMeterId)) {
                        devCollectDeviceEntity.setCategoryCode(flowMeter);
                    } else {
                        continue;
                    }

                    TollGasUserEntity tollGasUserEntity = gasUsers.get(yqdzId);
                    if (tollGasUserEntity != null) {
                        devCollectDeviceEntity.setGasUserId(tollGasUserEntity.getId());
                        devCollectDeviceEntity.setGasUserCode(tollGasUserEntity.getCode());
                        devCollectDeviceEntity.setGasUserAddress(tollGasUserEntity.getAddress());
                        devCollectDeviceEntity.setGasUserName(tollGasUserEntity.getName());
                    } else {
                        continue;
                    }

                    Integer typeId = collectDeviceTypes.get(mtId);
                    if (typeId != null) {
                        devCollectDeviceEntity.setTypeId(typeId);
                    } else {
                        devCollectDeviceEntity.setTypeId(0);
                    }

                    devCollectDeviceEntity.setIotDeviceId(iotDevices.get(parentNodeId));

                    UsrDeptEntity usrDeptEntity = userDepts.get(deptCode);
                    if (usrDeptEntity != null) {
                        devCollectDeviceEntity.setDeptId(usrDeptEntity.getId());
                        devCollectDeviceEntity.setDeptCode(usrDeptEntity.getCode());
                    } else {
                        devCollectDeviceEntity.setDeptId(0);
                    }

                    if ("1".equals(pressureUnit)) {
                        devCollectDeviceEntity.setPressureUnit("3");
                    }  else if ("2".equals(pressureUnit)) {
                        devCollectDeviceEntity.setPressureUnit("2");
                    } else if ("3".equals(pressureUnit)) {
                        devCollectDeviceEntity.setPressureUnit("1");
                    }

                    devCollectDeviceEntity.setCompanyId(Integer.parseInt(companyId));
                    devCollectDeviceEntity.setInstallTime(installTime);
                    devCollectDeviceEntity.setCreateTime(new Date());
                    devCollectDeviceEntity.setCreateUserId(0);
                    devCollectDeviceEntity.setResourceCode(resourceCode);
                    devCollectDeviceEntity.setIsValid(CommonOptions.YES_NO.YES);
                    devCollectDeviceEntity.setState("1");
                    devCollectDeviceDao.insert(devCollectDeviceEntity);

                    addCount++;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        long end = new Date().getTime();
        logger.info("同步采集设备结束: " + (end - start) / 1000 + "s");
        logger.info("同步时间: " + (end - start) / 1000 + "s");
        logger.info("更新数量: " + updateCount + "条");
        logger.info("新增数量: " + addCount + "条");
    }

    public void syncCollectDeviceStatusInfo() {
        int updateCount = 0;
        long start = new Date().getTime();

        List<DevCollectDeviceEntity> devCollectDeviceEntities = devCollectDeviceDao.selectByExample(new DevCollectDeviceExample());

        List<DevCollectDeviceEntity> updateCollectDevices = new ArrayList<>();
        for (DevCollectDeviceEntity devCollectDeviceEntity :
        devCollectDeviceEntities) {
            try {
                //查询最近一条数据
                Map<String, Object> criteriaMap = new HashMap<>();
                criteriaMap.put("collectDeviceId", devCollectDeviceEntity.getId());
                DevCollectDataEntity lastCollectData = devCollectDataCustomDao.selectLastCollectData(criteriaMap);
                if (lastCollectData == null) continue;

                devCollectDeviceEntity.setLastCollectTime(lastCollectData.getCurrentTm());
                devCollectDeviceEntity.setCurrentReading(lastCollectData.getCurrentValue());
                devCollectDeviceEntity.setCurrentCellVoltage(lastCollectData.getCellVoltage());
                devCollectDeviceEntity.setCurrentValveStatusCode(lastCollectData.getValveStatusCode());
                devCollectDeviceEntity.setUpdateUserId(0);
                devCollectDeviceEntity.setUpdateTime(new Date());

                updateCollectDevices.add(devCollectDeviceEntity);
                updateCount++;
                if (updateCollectDevices.size() == 1000) {
                    devCollectDeviceCustomDao.updateBatch(updateCollectDevices);
                    updateCollectDevices = new ArrayList<>();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        if (updateCollectDevices.size() > 0) {
            devCollectDeviceCustomDao.updateBatch(updateCollectDevices);
        }

        long end = new Date().getTime();
        logger.info("同步采集设备状态信息结束: " + (end - start) / 1000 + "s");
        logger.info("同步时间: " + (end - start) / 1000 + "s");
        logger.info("更新数量: " + updateCount + "条");
    }

    public void syncRegulatorDevice() {
        int addCount = 0;
        int updateCount = 0;
        long start = new Date().getTime();

        //同步调压箱
        List<Map<String, Object>> regulatorBoxes = oaDao.select1();
        for (Map<String, Object> regulatorBox:
        regulatorBoxes) {
            try {
                Integer regulatorId = null;

                String zid = HzhrTypeUtil.object2string(regulatorBox.get("ZID"));
                if (!StringUtils.isEmpty(zid)) {
                    String CODE = HzhrTypeUtil.object2string(regulatorBox.get("CODE"));
                    String MANUFACTURER = HzhrTypeUtil.object2string(regulatorBox.get("MANUFACTURER"));
                    String LOCATION = HzhrTypeUtil.object2string(regulatorBox.get("LOCATION"));
                    String ORGCODE = HzhrTypeUtil.object2string(regulatorBox.get("ORGCODE"));
                    String DEPTNAME = HzhrTypeUtil.object2string(regulatorBox.get("DEPTNAME"));
                    String PERSONCODE = HzhrTypeUtil.object2string(regulatorBox.get("PERSONCODE"));
                    String PERSONNAME = HzhrTypeUtil.object2string(regulatorBox.get("PERSONNAME"));
                    String START_DATE = HzhrTypeUtil.object2string(regulatorBox.get("START_DATE"));


                    DevCollectDeviceExample example = new DevCollectDeviceExample();
                    example.createCriteria().andOutIdEqualTo(zid);
                    List<DevCollectDeviceEntity> devCollectDeviceEntities = devCollectDeviceDao.selectByExample(example);
                    if (devCollectDeviceEntities.size() > 0) {
                        DevCollectDeviceEntity devCollectDeviceEntity = devCollectDeviceEntities.get(0);
                        devCollectDeviceEntity.setCode(CODE);
                        devCollectDeviceEntity.setDes("调压箱 " + CODE);
                        devCollectDeviceEntity.setInstallAddress(LOCATION);
                        devCollectDeviceEntity.setRegulatorDeviceProdFactory(MANUFACTURER);
                        devCollectDeviceEntity.setUpdateTime(new Date());
                        devCollectDeviceEntity.setUpdateUserId(0);
                        devCollectDeviceEntity.setState("1");
                        devCollectDeviceDao.updateByExampleSelective(devCollectDeviceEntity, example);
                        regulatorId = devCollectDeviceEntity.getId();
                        updateCount++;
                    } else {
                        DevCollectDeviceEntity devCollectDeviceEntity = new DevCollectDeviceEntity();
                        devCollectDeviceEntity.setOutId(zid);
                        devCollectDeviceEntity.setCode(CODE);
                        devCollectDeviceEntity.setDes("调压箱 " + CODE);
                        devCollectDeviceEntity.setCategoryCode("7");
                        devCollectDeviceEntity.setCompanyId(9);
                        devCollectDeviceEntity.setInstallAddress(LOCATION);
                        devCollectDeviceEntity.setRegulatorDeviceProdFactory(MANUFACTURER);
                        devCollectDeviceEntity.setManagementName(DEPTNAME);
                        if (!StringUtils.isEmpty(PERSONCODE)) {
                            Integer manangeUserId = userCustomDao.select6(PERSONCODE);
                            devCollectDeviceEntity.setManageUserId(manangeUserId);
                        }
                        devCollectDeviceEntity.setManageUserName(PERSONNAME);
                        String code = ORGCODE.replaceFirst("00", "9-01");
                        Map<String, Object> map = userCustomDao.select7(code);
                        if (map == null) continue;
                        devCollectDeviceEntity.setDeptId(HzhrTypeUtil.object2integer(map.get("ID")));
                        devCollectDeviceEntity.setDeptCode(code);
                        devCollectDeviceEntity.setResourceCode(HzhrTypeUtil.object2string(map.get("RESOURCE_CODE")));
                        devCollectDeviceEntity.setUsingDate(HzhrDateUtil.strToDate(START_DATE));
                        devCollectDeviceEntity.setCreateTime(new Date());
                        devCollectDeviceEntity.setCreateUserId(0);
                        devCollectDeviceEntity.setState("1");
                        devCollectDeviceEntity.setIsValid("1");
                        devCollectDeviceDao.insert(devCollectDeviceEntity);
                        regulatorId = devCollectDeviceEntity.getId();
                        addCount++;
                    }
                }

                if (regulatorId != null) {
                    //添加信息卡
                    DevDeviceInfoCardExample devDeviceInfoCardExample = new DevDeviceInfoCardExample();
                    devDeviceInfoCardExample.createCriteria().andDeviceIdEqualTo(regulatorId).andIsValidEqualTo("1");
                    int count = devDeviceInfoCardDao.countByExample(devDeviceInfoCardExample);
                    if (count == 0) {
                        DevDeviceInfoCardEntity devDeviceInfoCardEntity = new DevDeviceInfoCardEntity();
                        devDeviceInfoCardEntity.setDeviceId(regulatorId);
                        devDeviceInfoCardEntity.setCreateTime(new Date());
                        devDeviceInfoCardEntity.setCreateUserId(0);
                        devDeviceInfoCardEntity.setIsValid("1");
                        devDeviceInfoCardEntity.setState("1");
                        devDeviceInfoCardDao.insert(devDeviceInfoCardEntity);
                    }

                    //添加维护卡
                    String year = HzhrDateUtil.dateToStr(new Date(), "yyyy");
                    DevDeviceMaintenaceCardExample devDeviceInfoCardExample1 = new DevDeviceMaintenaceCardExample();
                    devDeviceInfoCardExample1.createCriteria().andDeviceIdEqualTo(regulatorId).andYearEqualTo(year).andIsValidEqualTo("1");
                    int count1 = devDeviceMaintenaceCardDao.countByExample(devDeviceInfoCardExample1);
                    if (count1 == 0) {
                        DevDeviceMaintenaceCardEntity devDeviceMaintenaceCardEntity = new DevDeviceMaintenaceCardEntity();
                        devDeviceMaintenaceCardEntity.setDeviceId(regulatorId);
                        devDeviceMaintenaceCardEntity.setYear(year);
                        devDeviceMaintenaceCardEntity.setCreateTime(new Date());
                        devDeviceMaintenaceCardEntity.setCreateUserId(0);
                        devDeviceMaintenaceCardEntity.setIsValid("1");
                        devDeviceMaintenaceCardEntity.setState("1");
                        devDeviceMaintenaceCardDao.insert(devDeviceMaintenaceCardEntity);
                    }
                }
            } catch (Throwable e) {
                logger.error("调压设备同步异常", e);
            }
        }

        //同步调压柜
        List<Map<String, Object>> regulatorTanks = oaDao.select2();
        for (Map<String, Object> regulatorTank:
                regulatorTanks) {
            try {
                Integer regulatorId = null;

                String zid = HzhrTypeUtil.object2string(regulatorTank.get("ZID"));
                if (!StringUtils.isEmpty(zid)) {
                    String CODE = HzhrTypeUtil.object2string(regulatorTank.get("CODE"));
                    String MANUFACTURER = HzhrTypeUtil.object2string(regulatorTank.get("MANUFACTURER"));
                    String LOCATION = HzhrTypeUtil.object2string(regulatorTank.get("LOCATION"));
                    String ORGCODE = HzhrTypeUtil.object2string(regulatorTank.get("ORGCODE"));
                    String DEPTNAME = HzhrTypeUtil.object2string(regulatorTank.get("DEPTNAME"));
                    String PERSONCODE = HzhrTypeUtil.object2string(regulatorTank.get("PERSONCODE"));
                    String PERSONNAME = HzhrTypeUtil.object2string(regulatorTank.get("PERSONNAME"));
                    String START_DATE = HzhrTypeUtil.object2string(regulatorTank.get("START_DATE"));


                    DevCollectDeviceExample example = new DevCollectDeviceExample();
                    example.createCriteria().andOutIdEqualTo(zid);
                    List<DevCollectDeviceEntity> devCollectDeviceEntities = devCollectDeviceDao.selectByExample(example);
                    if (devCollectDeviceEntities.size() > 0) {
                        DevCollectDeviceEntity devCollectDeviceEntity = devCollectDeviceEntities.get(0);
                        devCollectDeviceEntity.setCode(CODE);
                        devCollectDeviceEntity.setDes("调压柜 " + CODE);
                        devCollectDeviceEntity.setInstallAddress(LOCATION);
                        devCollectDeviceEntity.setRegulatorDeviceProdFactory(MANUFACTURER);
                        devCollectDeviceEntity.setUpdateTime(new Date());
                        devCollectDeviceEntity.setUpdateUserId(0);
                        devCollectDeviceEntity.setState("1");
                        devCollectDeviceDao.updateByExampleSelective(devCollectDeviceEntity, example);
                        regulatorId = devCollectDeviceEntity.getId();
                        updateCount++;
                    } else {
                        DevCollectDeviceEntity devCollectDeviceEntity = new DevCollectDeviceEntity();
                        devCollectDeviceEntity.setOutId(zid);
                        devCollectDeviceEntity.setCode(CODE);
                        devCollectDeviceEntity.setDes("调压柜 " + CODE);
                        devCollectDeviceEntity.setCategoryCode("8");
                        devCollectDeviceEntity.setCompanyId(9);
                        devCollectDeviceEntity.setInstallAddress(LOCATION);
                        devCollectDeviceEntity.setRegulatorDeviceProdFactory(MANUFACTURER);
                        devCollectDeviceEntity.setManagementName(DEPTNAME);
                        if (!StringUtils.isEmpty(PERSONCODE)) {
                            Integer manangeUserId = userCustomDao.select6(PERSONCODE);
                            devCollectDeviceEntity.setManageUserId(manangeUserId);
                        }
                        devCollectDeviceEntity.setManageUserName(PERSONNAME);
                        String code = ORGCODE.replaceFirst("00", "9-01");
                        Map<String, Object> map = userCustomDao.select7(code);
                        if (map == null) continue;
                        devCollectDeviceEntity.setDeptId(HzhrTypeUtil.object2integer(map.get("ID")));
                        devCollectDeviceEntity.setDeptCode(code);
                        devCollectDeviceEntity.setResourceCode(HzhrTypeUtil.object2string(map.get("RESOURCE_CODE")));
                        devCollectDeviceEntity.setUsingDate(HzhrDateUtil.strToDate(START_DATE));
                        devCollectDeviceEntity.setCreateTime(new Date());
                        devCollectDeviceEntity.setCreateUserId(0);
                        devCollectDeviceEntity.setState("1");
                        devCollectDeviceEntity.setIsValid("1");
                        devCollectDeviceDao.insert(devCollectDeviceEntity);
                        regulatorId = devCollectDeviceEntity.getId();
                        addCount++;
                    }
                }


                if (regulatorId != null) {
                    //添加信息卡
                    DevDeviceInfoCardExample devDeviceInfoCardExample = new DevDeviceInfoCardExample();
                    devDeviceInfoCardExample.createCriteria().andDeviceIdEqualTo(regulatorId).andIsValidEqualTo("1");
                    int count = devDeviceInfoCardDao.countByExample(devDeviceInfoCardExample);
                    if (count == 0) {
                        DevDeviceInfoCardEntity devDeviceInfoCardEntity = new DevDeviceInfoCardEntity();
                        devDeviceInfoCardEntity.setDeviceId(regulatorId);
                        devDeviceInfoCardEntity.setCreateTime(new Date());
                        devDeviceInfoCardEntity.setCreateUserId(0);
                        devDeviceInfoCardEntity.setIsValid("1");
                        devDeviceInfoCardEntity.setState("1");
                        devDeviceInfoCardDao.insert(devDeviceInfoCardEntity);
                    }

                    //添加维护卡
                    String year = HzhrDateUtil.dateToStr(new Date(), "yyyy");
                    DevDeviceMaintenaceCardExample devDeviceInfoCardExample1 = new DevDeviceMaintenaceCardExample();
                    devDeviceInfoCardExample1.createCriteria().andDeviceIdEqualTo(regulatorId).andYearEqualTo(year).andIsValidEqualTo("1");
                    int count1 = devDeviceMaintenaceCardDao.countByExample(devDeviceInfoCardExample1);
                    if (count1 == 0) {
                        DevDeviceMaintenaceCardEntity devDeviceMaintenaceCardEntity = new DevDeviceMaintenaceCardEntity();
                        devDeviceMaintenaceCardEntity.setDeviceId(regulatorId);
                        devDeviceMaintenaceCardEntity.setYear(year);
                        devDeviceMaintenaceCardEntity.setCreateTime(new Date());
                        devDeviceMaintenaceCardEntity.setCreateUserId(0);
                        devDeviceMaintenaceCardEntity.setIsValid("1");
                        devDeviceMaintenaceCardEntity.setState("1");
                        devDeviceMaintenaceCardDao.insert(devDeviceMaintenaceCardEntity);
                    }
                }
            } catch (Throwable e) {
                logger.error("调压设备同步异常", e);
            }
        }

        long end = new Date().getTime();
        logger.info("同步调压设备结束: " + (end - start) / 1000 + "s");
        logger.info("同步时间: " + (end - start) / 1000 + "s");
        logger.info("更新数量: " + updateCount + "条");
        logger.info("新增数量: " + addCount + "条");
    }

    public void syncRegulatorDevice_one(String code1) {
        int addCount = 0;
        int updateCount = 0;
        long start = new Date().getTime();

        List<Map<String, Object>> regulatorBoxes = oaDao.select3(code1);
        for (Map<String, Object> regulatorBox:
                regulatorBoxes) {
            try {
                Integer regulatorId = null;

                String zid = HzhrTypeUtil.object2string(regulatorBox.get("ZID"));
                if (!StringUtils.isEmpty(zid)) {
                    String CODE = HzhrTypeUtil.object2string(regulatorBox.get("CODE"));
                    String MANUFACTURER = HzhrTypeUtil.object2string(regulatorBox.get("MANUFACTURER"));
                    String LOCATION = HzhrTypeUtil.object2string(regulatorBox.get("LOCATION"));
                    String ORGCODE = HzhrTypeUtil.object2string(regulatorBox.get("ORGCODE"));
                    String DEPTNAME = HzhrTypeUtil.object2string(regulatorBox.get("DEPTNAME"));
                    String PERSONCODE = HzhrTypeUtil.object2string(regulatorBox.get("PERSONCODE"));
                    String PERSONNAME = HzhrTypeUtil.object2string(regulatorBox.get("PERSONNAME"));
                    String START_DATE = HzhrTypeUtil.object2string(regulatorBox.get("START_DATE"));
                    String NAME = HzhrTypeUtil.object2string(regulatorBox.get("NAME"));


                    DevCollectDeviceExample example = new DevCollectDeviceExample();
                    example.createCriteria().andOutIdEqualTo(zid);
                    List<DevCollectDeviceEntity> devCollectDeviceEntities = devCollectDeviceDao.selectByExample(example);
                    if (devCollectDeviceEntities.size() > 0) {
                        DevCollectDeviceEntity devCollectDeviceEntity = devCollectDeviceEntities.get(0);
                        devCollectDeviceEntity.setCode(CODE);
                        devCollectDeviceEntity.setDes(NAME + " " + CODE);
                        devCollectDeviceEntity.setInstallAddress(LOCATION);
                        devCollectDeviceEntity.setRegulatorDeviceProdFactory(MANUFACTURER);
                        devCollectDeviceEntity.setUpdateTime(new Date());
                        devCollectDeviceEntity.setUpdateUserId(0);
                        devCollectDeviceEntity.setState("1");
                        devCollectDeviceDao.updateByExampleSelective(devCollectDeviceEntity, example);
                        regulatorId = devCollectDeviceEntity.getId();
                        updateCount++;
                    } else {
                        DevCollectDeviceEntity devCollectDeviceEntity = new DevCollectDeviceEntity();
                        devCollectDeviceEntity.setOutId(zid);
                        devCollectDeviceEntity.setCode(CODE);
                        devCollectDeviceEntity.setDes(NAME + " " + CODE);
                        if ("调压箱".equals(NAME)) {
                            devCollectDeviceEntity.setCategoryCode("7");
                        }
                        if ("调压柜".equals(NAME)) {
                            devCollectDeviceEntity.setCategoryCode("8");
                        }
                        devCollectDeviceEntity.setCompanyId(9);
                        devCollectDeviceEntity.setInstallAddress(LOCATION);
                        devCollectDeviceEntity.setRegulatorDeviceProdFactory(MANUFACTURER);
                        devCollectDeviceEntity.setManagementName(DEPTNAME);
                        if (!StringUtils.isEmpty(PERSONCODE)) {
                            Integer manangeUserId = userCustomDao.select6(PERSONCODE);
                            devCollectDeviceEntity.setManageUserId(manangeUserId);
                        }
                        devCollectDeviceEntity.setManageUserName(PERSONNAME);
                        String code = ORGCODE.replaceFirst("00", "9-01").replaceFirst("00", "");
                        Map<String, Object> map = userCustomDao.select7(code);
                        if (map == null) continue;
                        devCollectDeviceEntity.setDeptId(HzhrTypeUtil.object2integer(map.get("ID")));
                        devCollectDeviceEntity.setDeptCode(code);
                        devCollectDeviceEntity.setResourceCode(HzhrTypeUtil.object2string(map.get("RESOURCE_CODE")));
                        devCollectDeviceEntity.setUsingDate(HzhrDateUtil.strToDate(START_DATE));
                        devCollectDeviceEntity.setCreateTime(new Date());
                        devCollectDeviceEntity.setCreateUserId(0);
                        devCollectDeviceEntity.setState("1");
                        devCollectDeviceEntity.setIsValid("1");
                        devCollectDeviceDao.insert(devCollectDeviceEntity);
                        regulatorId = devCollectDeviceEntity.getId();
                        addCount++;
                    }
                }

                if (regulatorId != null) {
                    //添加信息卡
                    DevDeviceInfoCardExample devDeviceInfoCardExample = new DevDeviceInfoCardExample();
                    devDeviceInfoCardExample.createCriteria().andDeviceIdEqualTo(regulatorId).andIsValidEqualTo("1");
                    int count = devDeviceInfoCardDao.countByExample(devDeviceInfoCardExample);
                    if (count == 0) {
                        DevDeviceInfoCardEntity devDeviceInfoCardEntity = new DevDeviceInfoCardEntity();
                        devDeviceInfoCardEntity.setDeviceId(regulatorId);
                        devDeviceInfoCardEntity.setCreateTime(new Date());
                        devDeviceInfoCardEntity.setCreateUserId(0);
                        devDeviceInfoCardEntity.setIsValid("1");
                        devDeviceInfoCardEntity.setState("1");
                        devDeviceInfoCardDao.insert(devDeviceInfoCardEntity);
                    }

                    //添加维护卡
                    String year = HzhrDateUtil.dateToStr(new Date(), "yyyy");
                    DevDeviceMaintenaceCardExample devDeviceInfoCardExample1 = new DevDeviceMaintenaceCardExample();
                    devDeviceInfoCardExample1.createCriteria().andDeviceIdEqualTo(regulatorId).andYearEqualTo(year).andIsValidEqualTo("1");
                    int count1 = devDeviceMaintenaceCardDao.countByExample(devDeviceInfoCardExample1);
                    if (count1 == 0) {
                        DevDeviceMaintenaceCardEntity devDeviceMaintenaceCardEntity = new DevDeviceMaintenaceCardEntity();
                        devDeviceMaintenaceCardEntity.setDeviceId(regulatorId);
                        devDeviceMaintenaceCardEntity.setYear(year);
                        devDeviceMaintenaceCardEntity.setCreateTime(new Date());
                        devDeviceMaintenaceCardEntity.setCreateUserId(0);
                        devDeviceMaintenaceCardEntity.setIsValid("1");
                        devDeviceMaintenaceCardEntity.setState("1");
                        devDeviceMaintenaceCardDao.insert(devDeviceMaintenaceCardEntity);
                    }
                }
            } catch (Throwable e) {
                logger.error("调压设备同步异常", e);
            }
        }

        long end = new Date().getTime();
        logger.info("同步调压设备结束: " + (end - start) / 1000 + "s");
        logger.info("同步时间: " + (end - start) / 1000 + "s");
        logger.info("更新数量: " + updateCount + "条");
        logger.info("新增数量: " + addCount + "条");
    }

    public void syncLoraMeter() {
        int addCount = 0;
        int updateCount = 0;
        long startTime = new Date().getTime();

        String resident = tollOptionsService.getCode("GAS_USER_TYPE", "RESIDENTIAL_USER");
        String commercial = tollOptionsService.getCode("GAS_USER_TYPE", "COMMERCIAL_USER");

        int i = 0;
        while (true) {
            Integer count = 5000;
            Integer start =  i * count;

            //查询平台自建的lora表的代码
            List<String> codes = deviceDao.select14(start, count);
            for (String code :
                    codes) {
                try {
                    //根据平台自建的lora表的代码找到这些表的营销系统信息
                    Map<String, Object> loraMeter = smDao.select3(code);
                    if (loraMeter != null) {
                        String ORG_ID = HzhrTypeUtil.object2string(loraMeter.get("ORG_ID"));
                        String YQDZ_YQZH = HzhrTypeUtil.object2string(loraMeter.get("YQDZ_YQZH"));
                        String YQDZ_HZ_MC = HzhrTypeUtil.object2string(loraMeter.get("YQDZ_HZ_MC"));
                        String YQDZ_SM = HzhrTypeUtil.object2string(loraMeter.get("YQDZ_SM"));
                        String yqdzKhLx = HzhrTypeUtil.object2string(loraMeter.get("YQDZ_KH_LX"));

                        //根据orgId找到部门
                        String deptCode = ORG_ID.replaceFirst("0000", "9-01");
                        Map<String, Object> dept = userCustomDao.select7(deptCode);
                        if (dept == null) continue;

                        //根据yqdzYqzh找到燃气用户编号，如果过找不到燃气用户则自建燃气用户
                        Integer gasUserId = tollGasUserCustomDao.select3(YQDZ_YQZH);
                        if (gasUserId == null) {
                            TollGasUserEntity tollGasUserEntity = new TollGasUserEntity();
                            tollGasUserEntity.setCode(YQDZ_YQZH);
                            tollGasUserEntity.setName(YQDZ_HZ_MC != null ? YQDZ_HZ_MC : "未知");
                            tollGasUserEntity.setAddress(YQDZ_SM);
                            if ("1".equals(yqdzKhLx)) {
                                tollGasUserEntity.setTypeCode(commercial);
                            } else if ("2".equals(yqdzKhLx)) {
                                tollGasUserEntity.setTypeCode(resident);
                            } else {
                                tollGasUserEntity.setTypeCode("0");
                            }
                            tollGasUserEntity.setCompanyId(Integer.parseInt(companyId));
                            tollGasUserEntity.setDeptId(HzhrTypeUtil.object2integer(dept.get("ID")));
                            tollGasUserEntity.setCreateTime(new Date());
                            tollGasUserEntity.setCreateUserId(0);
                            tollGasUserEntity.setResourceCode(HzhrTypeUtil.object2string(dept.get("RESOURCE_CODE")));
                            tollGasUserEntity.setIsValid(CommonOptions.YES_NO.YES);
                            tollGasUserEntity.setState("1");
                            tollGasUserDao.insert(tollGasUserEntity);

                            gasUserId = tollGasUserEntity.getId();
                        }

                        //根据营销系统信息更新这些lora表
                        DevCollectDeviceEntity devCollectDeviceEntity = new DevCollectDeviceEntity();
                        devCollectDeviceEntity.setCompanyId(9);
                        devCollectDeviceEntity.setDeptId(HzhrTypeUtil.object2integer(dept.get("ID")));
                        devCollectDeviceEntity.setDeptCode(deptCode);
                        devCollectDeviceEntity.setResourceCode(HzhrTypeUtil.object2string(dept.get("RESOURCE_CODE")));
                        devCollectDeviceEntity.setGasUserId(gasUserId);
                        devCollectDeviceEntity.setGasUserName(YQDZ_HZ_MC);
                        devCollectDeviceEntity.setGasUserCode(YQDZ_YQZH);
                        devCollectDeviceEntity.setGasUserAddress(YQDZ_SM);
                        devCollectDeviceEntity.setUpdateUserId(0);
                        devCollectDeviceEntity.setUpdateTime(new Date());
                        DevCollectDeviceExample devCollectDeviceExample = new DevCollectDeviceExample();
                        devCollectDeviceExample.createCriteria().andCodeEqualTo(code).andIsValidEqualTo("1");
                        devCollectDeviceDao.updateByExampleSelective(devCollectDeviceEntity, devCollectDeviceExample);
                        updateCount++;
                    }
                } catch (Throwable e) {
                    logger.error("同步lora表信息异常", e);
                }
            }

            if (codes.size() < 5000) {
                break;
            }

            i++;
        }

        long endTime = new Date().getTime();
        logger.info("更新自建lora表信息结束: " + (endTime - startTime) / 1000 + "s");
        logger.info("同步时间: " + (endTime - startTime) / 1000 + "s");
        logger.info("更新数量: " + updateCount + "条");
    }
}
